/*
 *	seriallib.c
 *	Basic serial commands, directed at use by arduinolib
 *
 *	Originally authored by Ian Hills - icopy11@gmail.com
 * 	Copyright 2010
 *	Distributed under the terms of the GNU General Public License
 *	And is distributed with NO WARRANTY.
 *	You should have received a copy of the GNU General Public License
 *      along with this program. If not, see <http://www.gnu.org/licenses/>.
 */


#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>   /* file io*/
#include <termios.h> /* terminal definitions */


/*
 * int open_port(char *portname) - Open serial port portname. eg. /dev/ttyUSB0
 * Returns the port id on success or -1 on error.
 */

int
open_port(char *portname)
{
	int port; /* port id */


	port = open(portname, O_RDWR | O_NOCTTY | O_NDELAY);
	if (port == -1)
	{
		/*
		* Could not open the port.
		*/

		printf("error opening port");
	}
	else
		fcntl(port, F_SETFL, 0);

	return (port);

}

/*
 * void set_baud(int port, int rate) - set baudrate to a port
 *
 * must input baudrate in correct format eg B19200
 * see (site) for details
 */

void
set_baud(int port, int rate)
{
	struct termios options;

	/*
	 * Get the current options for the port.
	 */

	tcgetattr(port, &options);

	/*
	 * Set the tx and rx baud rates, they should really be the same.
	 */

	cfsetispeed(&options, rate);
	cfsetospeed(&options, rate);

	/*
	 * Enable the receiver and set local mode.
	 */

	options.c_cflag |= (CLOCAL | CREAD);

	/*
	 * write new options to the port.
	 */

	tcsetattr(port, TCSANOW, &options);
}

/*
 * void write_bytes(int port, char data[]) - write bytes to a port
 */

void
write_bytes(int port, unsigned char data[])
{
	write(port,data,strlen(data));
	usleep(2500);// may not be nessisary, or need to be tweeked.
}

/*
 * void read_bytes(int port, int count) - attempt to read count bytes from
 * a port and put them on a passed in string.
 * Returns number of bytes actually read.
 */

int
read_bytes(int port,char *buffer, int count)
{
	int bytecount = 0;
	bytecount = read(port,buffer,count);
	return bytecount;
}

/*
 * void set_read_delay(int port,int delay) - set the read bytes function to
 * wait for data.
 * delay == 0 no wait.
 * delay == 1 wait.
 */

void
set_read_delay(int port, int delay)
{
	if (delay == 0)
	 fcntl(port, F_SETFL, FNDELAY);
	else
	 fcntl(port, F_SETFL, 0);
}

/*
 * close_port(int port) - close port
 */

void
close_port(int port)
{
	close(port);
}
